package com.gxc.healthfood.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxc.healthfood.dto.RegisterDTO;
import com.gxc.healthfood.entity.Users;
import com.gxc.healthfood.service.UsersService;
import com.gxc.healthfood.mapper.UsersMapper;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author hasee
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-10-03 16:13:14
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

    @Override
    public Users findByUsername(String username) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Users findByEmail(String email) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean verifyLogin(String username, String password) {
        Users user = findByUsername(username);
        if (user == null) {
            return false;
        }
        
        // 直接对比明文密码
        return password.equals(user.getPasswordHash());
    }

    @Override
    public boolean registerUser(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (findByUsername(registerDTO.getUsername()) != null) {
            return false;
        }
        
        // 检查邮箱是否已存在
        if (findByEmail(registerDTO.getEmail()) != null) {
            return false;
        }
        
        // 创建用户对象
        Users user = new Users();
        user.setUsername(registerDTO.getUsername());
        user.setEmail(registerDTO.getEmail());
        
        // 直接保存明文密码
        user.setPasswordHash(registerDTO.getPassword());
        
        // 设置默认值
        user.setRole("USER"); // 默认用户角色
        user.setStatus("ACTIVE"); // 默认激活状态
        user.setCreatedAt(new Date());
        user.setUpdatedAt(new Date());
        
        // 保存用户
        return save(user);
    }

    @Override
    public Users getUserProfile(Long userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public boolean updateUserProfile(Users user) {
        if (user == null || user.getId() == null) {
            return false;
        }
        
        // 设置更新时间
        user.setUpdatedAt(new Date());
        
        // 只更新非空字段
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        
        return baseMapper.update(user, queryWrapper) > 0;
    }
}




